
<template>
  <a-card :bordered="false" :bodyStyle="{ padding: '16px', height: '100%' }">
    <div class="table-page-search-wrapper" style="padding-left:10px;padding-right:10px;">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="6" :sm="24">
            <a-form-item label="搜索费用">
              <a-input
                v-model="keywords"
                placeholder="请输入费用名称(回车搜索)"
                @pressEnter="$refs.table.refresh(true)"
              >
                <a-tooltip slot="suffix" title="请输入费用名称">
                  <a-icon
                    type="search"
                    style="color: rgba(0,0,0,.45)"
                    @click="$refs.table.refresh(true)"
                  />
                </a-tooltip>
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="启用状态">
              <a-checkbox @change="openEnable" :checked="openChecked">启用</a-checkbox>
              <a-checkbox @change="closeEnable" :checked="closeChecked">停用</a-checkbox>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" style="margin-right:20px;" @click="visibles=true">新建费用</a-button>
    </div>
    <!-- <a-alert type="warning" message="费用的售卖详情可在“财务-收据明细”中查看" banner class="expand_warning" /> -->
    <s-table
      :columns="columns"
      :data="loadData"
      class="user_management_table"
      :rowKey="(record) => record.id"
      ref="table"
      style="margin-top:20px;"
      :pagination="pagination"
    >
      <span slot="is_enable" slot-scope="text,record">
        <a-switch :checked="text==1?true:false" @click="changeType(text,record)" />
      </span>
      <span slot="course" slot-scope="text, record">
        <span v-if="record.type==0">
          <span>未绑定</span>
        </span>
        <span v-if="record.type==2">
          <span v-for="(item,index) in record.course_arr" :key="index">
            <span>{{item.name}}</span>
            <span v-if="index!==record.course_arr.length-1">，</span>
          </span>
        </span>
        <span v-if="record.type==1">
          <span>全部课程</span>
        </span>
      </span>
      <span slot="action" slot-scope="text, record">
        <template>
          <a @click="handleEdit(record)">编辑</a>
          <a-divider type="vertical" />
          <a @click="del(record)">删除</a>
        </template>
      </span>
    </s-table>
    <create-form ref="createModal" @ok="handleOk" />

    <!-- 新建 -->
    <a-modal
      title="新建费用"
      :width="640"
      :visible="visibles"
      :confirmLoading="confirmLoading"
      @ok="modelSubmit"
      @cancel="modelCancel"
      :destroyOnClose="true"
      :keyboard="false"
      :zIndex="999"
    >
      <a-spin :spinning="confirmLoading">
        <a-form-model ref="ruleForm" :model="ruleForm" :rules="rules" v-bind="layout">
          <a-alert type="warning" message="请添加“课程”和“物品”以外的收费项目" banner class="expand_warning" />
          <a-form-model-item has-feedback label="费用名称" prop="name">
            <a-input
              v-model="ruleForm.name"
              autocomplete="off"
              style="width:250px;"
              placeholder="请输入费用名称，如“考试费”"
            />
          </a-form-model-item>
          <a-form-model-item label="售卖单价" prop="unit_price">
            <a-input-number
              :min="0"
              :step="0.01"
              v-model="ruleForm.unit_price"
              style="width:150px"
              placeholder="请输入售卖单价  "
            />&nbsp;元
          </a-form-model-item>
          <a-form-model-item label="绑定课程">
            <a-radio-group name="radioGroup" v-model="ruleForm.type">
              <a-radio :value="0">不绑定课程</a-radio>
              <a-radio :value="1">绑定全部课程</a-radio>
              <a-radio :value="2">绑定部分课程</a-radio>
            </a-radio-group>
            <div v-if="ruleForm.type==2">
              <a @click="showComponents('add')">添加课程</a>
              <div
                v-if="ruleForm.course_arr!==''"
                style="width:320px;overflow: hidden;text-overflow: ellipsis;white-space:nowrap;"
              >
                <span v-for="(item,index) in ruleForm.course_arr" :key="index">
                  <span>{{item.name}}</span>
                  <span v-if="index<ruleForm.course_arr.length-1">,</span>
                </span>
              </div>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
    <!-- 编辑 -->
    <a-modal
      title="编辑"
      :width="640"
      :visible="visiblesEdit"
      :confirmLoading="confirmLoading"
      @ok="modelEditSubmit"
      @cancel="modelEditCancel"
      :destroyOnClose="true"
      :keyboard="false"
      :zIndex="999"
    >
      <a-spin :spinning="confirmLoading">
        <a-form-model ref="ruleFormEdit" :model="ruleFormEdit" :rules="rules" v-bind="layout">
          <a-form-model-item has-feedback label="费用名称" prop="name">
            <a-input
              v-model="ruleFormEdit.name"
              style="width:250px;"
              autocomplete="off"
              placeholder="请输入费用名称，如“考试费”"
            />
          </a-form-model-item>
          <a-form-model-item label="售卖单价" prop="unit_price">
            <a-input-number
              :min="0"
              :step="0.01"
              v-model="ruleFormEdit.unit_price"
              style="width:150px"
              placeholder="请输入售卖单价  "
            />&nbsp;元
          </a-form-model-item>
          <a-form-model-item label="绑定课程">
            <a-radio-group name="radioGroup" v-model="ruleFormEdit.type" :default-value="1">
              <a-radio :value="0">不绑定课程</a-radio>
              <a-radio :value="1">绑定全部课程</a-radio>
              <a-radio :value="2">绑定部分课程</a-radio>
            </a-radio-group>
            <div v-if="ruleFormEdit.type==2">
              <a @click="showComponents('edit')">添加课程</a>
              <div
                v-if="ruleFormEdit.course_arr!==''"
                style="width:320px;overflow: hidden;text-overflow: ellipsis;white-space:nowrap;"
              >
                <span v-for="(item,index) in ruleFormEdit.course_arr" :key="index">
                  <span>{{item.name}}</span>
                  <span v-if="index<ruleFormEdit.course_arr.length-1">,</span>
                </span>
              </div>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </a-modal>
    <course-model ref="course" @receive="receiveData"></course-model>
  </a-card>
</template>

<script>
import moment from 'moment'
import { STable, Ellipsis } from '@/components'
import CreateForm from '../../list/modules/CreateForm'
import courseModel from '@/components/course'
import { getRoleList, getServiceList } from '@/api/manage'
import { costList, changeCostType, costDel, costCreate, costEdit } from '@/api/courseCharge'
export default {
  name: 'TableList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    courseModel
  },
  data() {
    return {
      store_user: null,
      mdl: {},
      visibles: false,
      visiblesEdit: false,
      ruleForm: {
        name: '',
        unit_price: '',
        remark: '',
        course_arr: [],
        type: 0
      },
      ruleFormEdit: {
        name: '',
        unit_price: '',
        remark: '',
        course_arr: [],
        type: 0
      },
      rules: {
        name: [{ required: true, message: '请输入费用名称  ' }],
        unit_price: [{ required: true, message: '请输入售卖单价  ' }]
      },
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      confirmLoading: false,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      keywords: '',
      queryParam: {
        school_id: this.$store.state.user.school,
        is_enable: null
      },
      pagination:{
        showTotal:total=>`共${total}条数据`,
      },
      // 表头
      columns: [
        {
          title: '费用名称',
          dataIndex: 'name',
          width: 150,
          fixed: 'left',
        },
        {
          title: '售卖单价',
          dataIndex: 'unit_price',
          customRender(unit_price) {
            return '￥' + unit_price
          }
        },
        {
          title: '绑定课程',
          dataIndex: 'course_arr',
          ellipsis: true,
          scopedSlots: { customRender: 'course' }
        },
        {
          title: '启用状态',
          dataIndex: 'is_enable',
          align: 'center',
          scopedSlots: { customRender: 'is_enable' }
        },
        {
          title: '操作',
          //   width: '100px',
          dataIndex: 'action',
          fixed: 'right',
          align: 'right',
          ellipsis: true,
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return costList(Object.assign(parameter, this.queryParam, { keywords: this.keywords })).then(res => {
          return res
        })
      },
      storageData: null,
      sendChildData: [],
      openChecked: false,
      closeChecked: false
    }
  },
  created() {
    this.store_user = this.$store.state.user
  },
  watch: {
    queryParam: {
      handler(val) {
        this.$refs.table.refresh()
      },
      immediate: false,
      deep: true
    }
  },
  methods: {
    modelSubmit() {
      if (this.ruleForm.type == 2 && this.ruleForm.course_arr.length == 0) {
        this.$message.error('请选择绑定课程，若您不需要绑定课程，请选择不绑定课程~')
        return
      }
      this.confirmLoading = true
      costCreate({
        name: this.ruleForm.name,
        unit_price: this.ruleForm.unit_price,
        school_id: this.store_user.school,
        course_arr: this.ruleForm.course_arr,
        type: this.ruleForm.type
      })
        .then(res => {
          this.$message.success('添加成功')
          this.confirmLoading = false
          this.visibles = false
          this.$refs.table.refresh()
          
          this.ruleForm = {
            name: '',
            unit_price: '',
            remark: '',
            course_arr: [],
            type: 0
          }
        })
        .catch(err => {
          this.$message.error(err.data.message || '添加失败')
          this.confirmLoading = false
        })
    },
    modelCancel() {
      //model
      this.visibles = false
    },
    modelEditSubmit() {
      //model
      if (this.ruleFormEdit.type == 2 && this.ruleFormEdit.course_arr.length == 0) {
        this.$message.error('请选择绑定课程，若您不需要绑定课程，请选择不绑定课程~')
        return
      }
      this.confirmLoading = true
      costEdit(
        {
          name: this.ruleFormEdit.name,
          unit_price: this.ruleFormEdit.unit_price,
          school_id: this.store_user.school,
          course_arr: this.ruleFormEdit.course_arr,
          type: this.ruleFormEdit.type
        },
        this.ruleFormEdit.id
      )
        .then(res => {
          this.$message.success('编辑成功')
          this.confirmLoading = false
          this.visiblesEdit = false
          this.$refs.table.refresh()
        })
        .catch(err => {
          this.$message.error(err.data.message || '编辑失败')
          this.confirmLoading = false
        })
    },
    modelEditCancel() {
      this.visiblesEdit = false
    },
    del(e) {
      let that = this
      this.$confirm({
        title: '提示',
        content: '确认删除？',
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk() {
          costDel(e.id)
            .then(res => {
              that.$message.success('删除成功')
              that.$refs.table.refresh(false)
            })
            .catch(err => {
              that.$message.error(err.data.message || '删除失败')
            })
        },
        onCancel() {
          console.log('Cancel')
        }
      })
    },
    changeType(data, e) {
      if (data == 2) {
        changeCostType({ is_enable: 1, school_id: this.$store.state.user.school }, e.id)
          .then(res => {
            this.$refs.table.refresh(false)
          })
          .catch(err => {
            this.$message.error(err.data.message || '更新状态失败')
          })
      } else {
        changeCostType({ is_enable: 2, school_id: this.$store.state.user.school }, e.id)
          .then(res => {
            this.$refs.table.refresh(false)
          })
          .catch(err => {
            this.$message.error(err.data.message || '更新状态失败')
          })
      }
    },
    handleEdit(record) {
      this.ruleFormEdit = JSON.parse(JSON.stringify(record))
      this.visiblesEdit = true
    },
    handleOk() {
      this.$refs.table.refresh()
    },
    showComponents(e) {
      this.storageData = e
      if (e == 'add') {
        let data = []
        this.ruleForm.course_arr.forEach(val => {
          data.push(val.id)
        })
        this.$refs.course.showModal(data)
      } else if (e == 'edit') {
        let data = []
        this.ruleFormEdit.course_arr.forEach(val => {
          data.push(val.id)
        })
        this.$refs.course.showModal(data)
      }
    },
    receiveData(data) {
      if (this.storageData == 'add') {
        this.ruleForm.course_arr = data
      } else if (this.storageData == 'edit') {
        this.ruleFormEdit.course_arr = data
      }
    },

    openEnable(e) {
      if (e.target.checked == true) {
        this.closeChecked = false
        this.queryParam.is_enable = 1
        this.openChecked = true
      } else {
        this.queryParam.is_enable = null
        this.openChecked = false
      }
    },
    closeEnable(e) {
      if (e.target.checked == true) {
        this.openChecked = false
        this.queryParam.is_enable = 2
        this.closeChecked = true
      } else {
        this.queryParam.is_enable = null
        this.closeChecked = false
      }
    }
  }
}
</script>
<style lang="less" scoped>
.expand_warning {
  margin: 0 0 16px 0;
  background-color: #fff0e7;
  border-radius: 4px;
}
</style>